其他
{mmtable2}: 再探三线表绘制
欢迎关注「R语言数据分析指南」
❝之前介绍如何使用「gt」包来制作三线表,最近发现一个新的R包「mmtable2」,它不仅整合了「gt」包而且语法风格与「ggplot2」高度一致采用图层叠加的方式来绘制表格,更加难得的是还支持通过 「%>%」 来绘制表格
❞
R如何优雅的绘制精美表格
安装并加载R包
devtools::install_github("ianmoran11/mmtable2")
library(gapminder)
library(tidyverse)
library(stringr)
library(gt)
library(mmtable2)
整合数据
gm_df <- gapminder_mm %>% filter(var != "Life expectancy")
style_list <- list(cell_borders(sides = "top",color = "grey"))
# A tibble: 6 x 5
country continent year var value
<chr> <fct> <int> <chr> <chr>
1 Australia Oceania 1992 Population 17.5
2 Australia Oceania 1997 Population 18.6
3 Australia Oceania 2002 Population 19.5
4 Australia Oceania 2007 Population 20.4
5 Botswana Africa 1992 Population 1.3
6 Botswana Africa 1997 Population 1.5
案例一
gm_df %>%
mmtable(cells = value) +
header_left(year) +
header_top(country) +
header_left_top(var) +
header_top_left(continent) +
header_format(var, scope = "table", style = style_list)
❝可以看到通过 「+」 来叠加图层绘制表格特别舒服
❞
案例二格式化表格
gapminder_mm %>%
filter(var != "Life expectancy") %>%
mmtable(cells = value) +
header_top(year) +
header_left(country) +
header_top_left(var) +
header_left_top(continent) +
cells_format(cell_predicate = T, style = list(cell_text(align = "right"))) +
header_format(header = year, style = list(cell_text(align = "right"))) +
header_format("all_cols", style = list(cell_text(weight = "bolder"))) +
header_format("all_rows", style = list(cell_text(weight = "bolder"))) +
header_format(continent, scope= "table",
style = list(cell_borders(sides = "top",color = "grey")))
案例三 通过 %>%连接数据
gapminder_mm %>%
filter(var != "Life expectancy") %>%
mmtable(cells = value, use_default_formats = T) %>%
add_header_top(year) %>%
add_header_left(country) %>%
add_header_top_left(var) %>%
add_header_left_top(continent) %>%
add_cells_format(cell_predicate = T,style = list(cell_text(align = "right",color="white"),
cell_fill(color="grey80"))) %>% # 定义文本填充颜色与字体
add_header_format(header = year,style =list(gt::cell_text(align = "right",color="black"),
gt::cell_fill(color = "lightcyan"))) %>% #定义标题行填充文本与颜色
add_header_format("all_cols", style = list(cell_text(weight = "bolder"))) %>%
add_header_format("all_rows", style = list(cell_text(weight = "bolder"))) %>%
cols_align(align="center",columns=1:2) %>% # 设置列宽
tab_options(table_body.hlines.color ="grey80",
table_body.hlines.width =px(2)
) %>% # 定义标题线条宽度,颜色
add_header_format(continent,scope= "table",
style = list(cell_borders(sides = c("top","bottom"),
color="white",weight = px(2))
)) # 定义文本线条颜色,宽度
❝「mmtable2」语法上兼容了「gt」包,提供了一种新的方法但是部分功能作者可能还是在开发中,但是绘制一个简单的三线表已经是绰绰有余了;感兴趣的小伙伴欢迎加入我微信,付费99元邀请您加入我的「VIP交流群」,同步获取每篇文档的代码并获得更多优质资料,同时「一整年公众号所有文档的数据及代码」会同步上传,同时还会配套精美的「Markdown文档」方便各位学习,公众号右下角可添加小编微信
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入VIP交流群,请在菜单栏处添加作者微信
往期推荐